package com.xh.petdogexpert.sys.service.imp;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.xh.petdogexpert.base.BaseException;
import com.xh.petdogexpert.sys.dto.Role;
import com.xh.petdogexpert.sys.service.ILoginService;
import com.xh.petdogexpert.sys.service.IRoleService;
import com.xh.petdogexpert.user.dto.User;
import com.xh.petdogexpert.user.mapper.UserMapper;

@Transactional
@Service
public class LoginServiceImp implements ILoginService {

	@Autowired
	UserMapper userMapper;

	@Autowired
	IRoleService roleService;

	@Autowired
	HttpSession httpSession;

	@Override
	public boolean login(User user) throws BaseException {

		user.setEmail(user.getNickname());
		
		User nUser = userMapper.loginValudate(user);
		System.out.println(nUser);;
		if (nUser != null) {
			Role role = new Role();
			role.setId(nUser.getRoleId());
			List<Role> roles = roleService.getRoleResources(role);
			if (roles.size() < 1)
				throw new BaseException("你没有任何权限");
			Role nRole = roles.get(0);
			nUser.setRole(nRole);
			httpSession.setAttribute("user", nUser);
			return true;
		} else {
			throw new BaseException("账号或密码错误");
		}

	}

	@Override
	public boolean logout() {
		httpSession.setAttribute("user", null);
		return true;
	}

}
